<?php

namespace app\common\model\goods;

use app\common\model\goods\Goods as GoodsGoods;
use app\common\model\order\Goods;
use app\common\model\order\Order;
use app\common\model\User;
use think\Model;


class Spec extends Model
{





    // 表名
    protected $name = 'goods_spec';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];


    /**
     * 判断商品是否能下单
     * @param int $product_id   商品id
     * @param int $num 数量
     * @return bool
     */
    public static function checkGoods($data)
    {
        $goods = $data['goods'];
        $product = $data['spec'];
        $user = User::get($data['user_id']);
        if (!isset($goods) || !$goods) {
            exception('商品【' . $goods['title'] . '】不存在');
        }
        if (!isset($product) || !$product || !$product['id']) {
            exception('商品【' . $goods['title'] . '】规格不存在');
        }
        if ($product['stock'] < $data['num']) {
            exception('商品【' . $goods['title'] . '】库存不足，不能下单');
        }
        if ($goods['status'] == 'hidden') {
            exception('商品【' . $goods['title'] . '】已下架，不能下单');
        }
        if ($goods['deletetime'] != null) {
            exception('商品【' . $goods['title'] . '】已删除，不能下单');
        }
        if (in_array($goods['type'], ['2', '4'])) {
            Order::check_goods(['id' => $goods['id'], 'uid' => $data['user_id'], 'num' => $data['num']]);
        }
    }
    /**
     * 增销减库
     * @param int $product_id   商品id
     * @param int $num 数量
     * @return bool
     */
    public static function reduceInventory($goods_id, $product_id, $num)
    {

        try {
            $product = self::get($product_id);
            $goods = GoodsGoods::get($goods_id);
            if ($product->stock < $num) {
                exception('库存不足');
            }
            $goods->setInc('sales', $num);
            $product->setDec('stock', $num);
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }
    /**
     * 减销增库
     * @param int $goods_id   商品id
     * @param int $num 数量
     * @return bool
     */
    public static function stockUp($goods_id, $product_id, $num)
    {
        try {
            $product = self::get($product_id);
            $goods = GoodsGoods::get($goods_id);
            if ($product->stock < $num) {
                exception('库存不足');
            }
            $goods->setDec('sales', $num);
            $product->setInc('stock', $num);
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
        return true;
    }
}
